package com.pb.infra.auth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.pb.infra.auth.entity.byd.Index;
import com.pb.infra.auth.entity.custom.PriviInterCustom;
import com.pb.infra.auth.entity.custom.PriviMenuCustom;
import com.pb.infra.auth.entity.pbsys.CapExtFileUpload;
import com.pb.infra.auth.entity.pbsys.FileDel;
import com.pb.infra.oth.entity.common.DictVO;
import com.pb.infra.oth.util.*;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.auth.mapper.CommonMapper;
import com.pb.infra.oth.exception.AppAuthException;
import com.pb.infra.oth.exception.ErrorCode;
import com.pb.infra.param.service.CapBaseInfoConfigService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 通用模块（业务逻辑类）
 *
 * @Author:liudebao
 * @Date: 2019/8/8
 */
@Slf4j
@Service
public class CommonService {

    /**
     * DAO映射对象
     */
    @Resource
    private CommonMapper commonMapper;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    @Resource
    private RedisUtil redisUtil;

    /**
     * redis数据访问
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 读取标准代码
     * @param type 标准代码类型
     * @return Result 返回数据
     */
    public Result selBusiCode(String type) {
        List<Map<String, Object>> mapList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("businessCode", type);
        List<Map<String, Object>> list = commonMapper.getBusiTable(map);
        if (list != null && list.size() > 0) {
            mapList = commonMapper.getMaBusiCode(list.get(0));
        }
        return Result.ok(mapList);
    }

    /**
     * 获取自增序号
     * @param str 类型
     * @return 唯一标识
     */
    public String getIdNumber(String str) {
        Map<String, Object> map = new HashMap<>();
        if ("0".equals(str)) {
            /*
             * YYYYMMDD+序号
             */
            map.put("serialNoType", "TXN-ID");
            map.put("serialNoId", "TXN-ID");
        } else if ("1".equals(str)) {
            /*
             * 从100000递增
             */
            map.put("serialNoType", "SERIAL");
            map.put("serialNoId", "SERIAL");
        } else if ("2".equals(str)) {
            /*
             * 标识+序号
             */
            map.put("serialNoType", "ID-SERIAL");
            map.put("serialNoId", "ID-SERIAL");
            return getIdNumber(str, "");
        } else if ("3".equals(str)) {
            /*
            *随机字符串（大小写字母+数字）
            */
            map.put("serialNoType", "RANDOM-STRING");
            map.put("serialNoId", "RANDOM-STRING");
            String ranStr="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            SecureRandom random = null;
            try {
                random = SecureRandom.getInstance("SHA1PRNG");
            }catch (NoSuchAlgorithmException e){
                log.error("");
                e.printStackTrace();
            }
            StringBuffer sb=new StringBuffer();
            for(int i=0;i<32;i++){
                int number =random.nextInt(62);
                sb.append(ranStr.charAt(number));
            }
            return sb.toString();
        }
        List<Map<String, Object>> list =  commonMapper.selectIdNumber(map);
        List<Map<String, Object>> list1 = commonMapper.selectInitId(map);
        try {
            if (list1 == null || list1.size() == 0) {
                throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_IDENT_ID);
            }
        } catch (AppAuthException e) {
            log.error(e.getMessage());
            return null;
        }
        if (list != null && list.size() > 0) {
            map.put("serialNo", Long.valueOf(list.get(0).get("serialNo").toString()) + Integer.parseInt(list1.get(0).get("incrementValue").toString()));
            commonMapper.updateIdNumber(map);
            if ("0".equals(str)) {
                return DateTimeUtil.getDate() + list.get(0).get("serialNo").toString();
            } else {
                return list.get(0).get("serialNo").toString();
            }
        } else {
            map.put("serialNo", Long.valueOf(list1.get(0).get("beginValue").toString()) + Integer.parseInt(list1.get(0).get("incrementValue").toString()));
            commonMapper.insertIdNumber(map);
            if ("0".equals(str)) {
                return DateTimeUtil.getDate() + list1.get(0).get("beginValue").toString();
            } else {
                return list1.get(0).get("beginValue").toString();
            }
        }
    }

    /**
     * 获取自增序号
     * @param str 类型 flag 序号前缀
     * @return 唯一标识
     */
    public String getIdNumber(String str, String flag) {
        Map<String, Object> map = new HashMap<>();
        if ("0".equals(str)) {
            /*
             * YYYYMMDD+序号
             */
            map.put("serialNoType", "TXN-ID");
            map.put("serialNoId", "TXN-ID");
            return getIdNumber(str);
        } else if ("1".equals(str)) {
            /*
             *从100000递增
             */
            map.put("serialNoType", "SERIAL");
            map.put("serialNoId", "SERIAL");
            return getIdNumber(str);
        } else if ("2".equals(str)) {
            /*
             *标识+序号
             */
            map.put("serialNoType", "ID-SERIAL");
            map.put("serialNoId", "ID-SERIAL");
        } else if ("3".equals(str)) {
            /*
             *随机字符串（大小写字母+数字）
             */
            map.put("serialNoType", "RANDOM-STRING");
            map.put("serialNoId", "RANDOM-STRING");
            String ranStr="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            SecureRandom random = null;
            try {
                random = SecureRandom.getInstance("SHA1PRNG");
            }catch (NoSuchAlgorithmException e){
                e.printStackTrace();
            }
            StringBuffer sb=new StringBuffer();
            for(int i=0;i<32;i++){
                int number =random.nextInt(62);
                sb.append(ranStr.charAt(number));
            }
            return sb.toString();
        }
        List<Map<String, Object>> list =  commonMapper.selectIdNumber(map);
        List<Map<String, Object>> list1 = commonMapper.selectInitId(map);
        try {
            if (list1 == null || list1.size() == 0) {
                throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_IDENT_ID);
            }
        } catch (AppAuthException e) {
            log.error(e.getMessage());
            return null;
        }
        if (list != null && list.size() > 0) {
            map.put("serialNo", Long.valueOf(list.get(0).get("serialNo").toString()) + Integer.parseInt(list1.get(0).get("incrementValue").toString()));
            commonMapper.updateIdNumber(map);
            if ("0".equals(str)) {
                return DateTimeUtil.getDate() + list.get(0).get("serialNo").toString();
            }else if ("2".equals(str)) {
                return flag + list.get(0).get("serialNo").toString();
            } else {
                return list.get(0).get("serialNo").toString();
            }
        } else {
            map.put("serialNo", Long.valueOf(list1.get(0).get("beginValue").toString()) + Integer.parseInt(list1.get(0).get("incrementValue").toString()));
            commonMapper.insertIdNumber(map);
            if ("0".equals(str)) {
                return DateTimeUtil.getDate() + list1.get(0).get("beginValue").toString();
            }else if ("2".equals(str)) {
                return flag + list1.get(0).get("beginValue").toString();
            } else {
                return list1.get(0).get("beginValue").toString();
            }
        }
    }

    /**
     * 读取数据库类型信息
     *
     * @return 类型集合
     */
    public Result selectBaseType() {
        List<Map<String, Object>> list = commonMapper.selectBaseType();
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询码值有效标识
     * @param map
     * @return 有效标识集合
     */
    public List<Map<String,Object>> selectCodeTypeList(Map<String,Object> map) {
        List<Map<String, Object>> list = commonMapper.selectCodeTypeList(map);
        return list;
    }

    /**
     * 查询数据存放类型
     * @return 数据存放类型
     */
    public Result selectStoreTypeList() {
        List<Map<String, Object>> list = commonMapper.selectStoreTypeList();
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询数据源类型
     * @return 数据源类型
     */
    public Result selSourceType() {
        List<Map<String, Object>> list = commonMapper.selSourceType();
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询数据源用途
     * @return 数据源用途
     */
    public Result selSourceUse() {
        List<Map<String, Object>> list = commonMapper.selSourceUse();
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询参数历史数据
     * @return 历史数据类型
     */
    public Result selHisData() {
        List<Map<String, Object>> list = commonMapper.selHisData();
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询法人列表
     * @param request
     * @return 法人列表
     */
    public Result selCorpList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        map.put("userId", userId);
        List<Map<String, Object>> list = commonMapper.selCorpList(map);
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询多法人法人+管理法人列表
     * @param request
     * @return 当前用户所有法人
     */
    public Result selDisCorp(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        map.put("userId", userId);
        List<Map<String, Object>> list = commonMapper.selDisCorp(map);
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询法人列表
     * @param map
     * @return 当前职位对应法人
     */
    public Result selRuleCorpList(Map<String, Object> map, HttpServletRequest request) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        map.put("userId", userId);
        UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
        map.put("positionId", userInfo.getPositionId());
        List<Map<String, Object>> list = commonMapper.selRuleCorpList(map);
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询用户职位信息
     * @param request
     * @return 用户职位
     */
    public Result selUserPosition(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = "";
        List<Map<String, Object>> list = new ArrayList<>();
        if (!StringUtil.isEmpty(claims)) {
            userId = (String)claims.get(jwtTokenConfig.getSub());
            map.put("userId", userId);
            list = commonMapper.selUserPosition(map);
            list.removeAll(Collections.singleton(null));
        }
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询主职位信息
     * @param request
     * @return 主职位信息
     */
    public Result selMainPositon(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = "";
        List<Map<String, Object>> list = new ArrayList<>();
        if (!StringUtil.isEmpty(claims)) {
            userId = (String)claims.get(jwtTokenConfig.getSub());
            map.put("userId", userId);
            list = commonMapper.selMainPosition(map);
            list.removeAll(Collections.singleton(null));
        }
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询职位信息，切换职位缓存数据变更
     * @param map
     * @return 职位信息
     */
    public Result selPositionInfo(Map<String, Object> map, HttpServletRequest request) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        map.put("userId", userId);
        List<Map<String, Object>> list = commonMapper.selPositionInfo(map);
        list.removeAll(Collections.singleton(null));
        /*List<Map<String, Object>> listMap = loginMapper.selUserData(userId);
        String orgId = "";
        String corpId = "";
        String levelId = "";
        String corpName = "";
        String structName = "";
        String deptId = "";
        String structId = "";
        UserInfo userInfo1 = (UserInfo)redisTemplate.opsForValue().get(token);
        if (listMap != null && listMap.size() > 0) {
            if (!StringUtil.isEmpty(listMap.get(0).get("orgId"))) {
                orgId = listMap.get(0).get("orgId").toString();
            }
            if (!StringUtil.isEmpty(listMap.get(0).get("corpId"))) {
                corpId = listMap.get(0).get("corpId").toString();
            }
            if (!StringUtil.isEmpty(listMap.get(0).get("levelId"))) {
                levelId = listMap.get(0).get("levelId").toString();
            }
            if (!StringUtil.isEmpty(listMap.get(0).get("structName"))) {
                structName = listMap.get(0).get("structName").toString();
            }
            if (!StringUtil.isEmpty(listMap.get(0).get("corpName"))) {
                corpName = listMap.get(0).get("corpName").toString();
            }
            if (!StringUtil.isEmpty(listMap.get(0).get("deptId"))) {
                deptId = listMap.get(0).get("deptId").toString();
            }
            if (!StringUtil.isEmpty(listMap.get(0).get("structId"))) {
                structId = listMap.get(0).get("structId").toString();
            }
            if (!StringUtil.isEmpty(listMap.get(0).get("structType"))) {
                if ("1".equals(listMap.get(0).get("structType").toString()) || "3".equals(listMap.get(0).get("structType").toString())) {
                    userInfo1.setOrgName(structName);
                } else if ("2".equals(listMap.get(0).get("structType").toString())) {
                    userInfo1.setDeptName(structName);
                }
            }
        }

        userInfo1.setOrgId(orgId);
        userInfo1.setCorpId(corpId);
        userInfo1.setCorpName(corpName);
        userInfo1.setOrgRank(levelId);
        userInfo1.setUserId(userId);
        userInfo1.setDeptId(deptId);
        userInfo1.setStructId(structId);
        userInfo1.setPositionId(map.get("positionId").toString());
        if (!StringUtil.isEmpty(token)) {
            if (redisTemplate.hasKey(token)) {
                redisTemplate.delete(token);
            }
            redisTemplate.opsForValue().set(token, userInfo1, 24L, TimeUnit.HOURS);
        }*/
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询按钮权限
     * @param map
     * @param request
     * @return
     */
    public Result selBtnAuthInfo(Map<String, Object> map, HttpServletRequest request) {
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        map.put("userId", userId);
        List<Map<String, Object>> btnAuthList = commonMapper.queryBtnAuth(map);
        map.put("btnAuthInfo", btnAuthList);
        return Result.ok(map);
    }

    /**
     * 查询所有法人信息
     * @return  所有法人信息
     */
    public Result selAllCorpList() {
        List<Map<String, Object>> list = commonMapper.selAllCorpList();
        list.removeAll(Collections.singleton(null));
        if (list != null && list.size() > 0) {
            return Result.ok(list);
        } else {
            return Result.OK_EMPTY;
        }
    }

    /**
     * 查询法人所属机构
     * @return 机构信息
     */
    public List<Map<String, Object>> getDimOrgTree(Map<String, Object> map, HttpServletRequest request) {
        if (!StringUtil.isEmpty(map.get("loginUser")) && Constant.OK.equals(map.get("loginUser").toString())) {
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            map.put("loginUser", userId);
        }
        List<Map<String, Object>> list = commonMapper.getCorpOrg(map);
        /*if (list != null && !StringUtil.isEmpty(map.get("corpId"))) {
            Set<String> set = new HashSet<>();
            for (int i = 0; i < list.size(); i++) {
                if (!StringUtil.isEmpty(list.get(i).get("nodePath"))) {
                    String nodePath = list.get(i).get("nodePath").toString();
                    String[] orgIds = nodePath.split("\\.");
                    if (orgIds.length > 0) {
                        for (int j = 0; j < orgIds.length; j++) {
                            if (!StringUtil.isEmpty(orgIds[j])) {
                                String corpId = commonMapper.selOrgByCorp(orgIds[j]);
                                if (corpId.equals(map.get("corpId").toString())) {
                                    set.add(orgIds[j]);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            List<String> list1 = new ArrayList<>(set);
            for (int j = 0; j < list1.size(); j++) {
                for (int i = 0; i < list.size(); i++) {
                    if (list1.get(j).equals(list.get(i).get("id").toString())) {
                        list.get(i).put("parentId", 0);
                        break;
                    }
                }
            }
        }*/
        return list;
    }

    /**
     * 查询组织架构树过滤部门
     * @param map
     * @param request
     * @return 机构树
     */
    public Result getOrgStTree(Map<String, Object> map, HttpServletRequest request) {
        if (!StringUtil.isEmpty(map.get("loginUser")) && Constant.OK.equals(map.get("loginUser").toString())) {
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            map.put("loginUser", userId);
        }
        List<Map<String, Object>> list = commonMapper.getCorpOrg1(map);
        /*if (list != null && !StringUtil.isEmpty(map.get("corpId"))) {
            Set<String> set = new HashSet<>();
            for (int i = 0; i < list.size(); i++) {
                if (!StringUtil.isEmpty(list.get(i).get("nodePath"))) {
                    String nodePath = list.get(i).get("nodePath").toString();
                    String[] orgIds = nodePath.split("\\.");
                    if (orgIds.length > 0) {
                        for (int j = 0; j < orgIds.length; j++) {
                            if (!StringUtil.isEmpty(orgIds[j])) {
                                String corpId = commonMapper.selOrgByCorp1(orgIds[j]);
                                if (corpId.equals(map.get("corpId").toString())) {
                                    set.add(orgIds[j]);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            List<String> list1 = new ArrayList<>(set);
            for (int j = 0; j < list1.size(); j++) {
                for (int i = 0; i < list.size(); i++) {
                    if (list1.get(j).equals(list.get(i).get("id").toString())) {
                        list.get(i).put("parentId", 0);
                        break;
                    }
                }
            }
        }*/
        return Result.ok(list);
    }

    /**
     * 查询所有数据权限
     * @param paramMap
     * @return 数据权限集合
     */
    public Result selAuthData(Map<String, Object> paramMap){
        List<Map<String, Object>> mapList = commonMapper.selTypeData(paramMap);
        List<Map<String, Object>> list = new ArrayList<>();
        if (mapList != null && mapList.size() > 0) {
            Map<String, Object> map = mapList.get(0);
            map.put("rghtType", paramMap.get("rghtType").toString());
            map.put("positionId", paramMap.get("positionId").toString());
            if (!StringUtil.isEmpty(paramMap.get("displayRght"))) {
                map.put("displayRght", paramMap.get("displayRght").toString());
            }
            if (!StringUtil.isEmpty(paramMap.get("editRght"))) {
                map.put("editRght", paramMap.get("editRght").toString());
            }
            if ("1".equals(map.get("tableType").toString())) {
                list = commonMapper.selAuthData(map);
                List<String> list1 = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    if (!StringUtil.isEmpty(list.get(i).get("parentId"))) {
                        boolean flag = false;
                        for (int j = 0; j < list.size(); j++) {
                            if (j != i) {
                                if (list.get(j).get("id").toString().equals(list.get(i).get("parentId").toString())) {
                                    flag = true;
                                    break;
                                }
                            }
                        }
                        if (!flag) {
                            list1.add(list.get(i).get("parentId").toString());
                        }
                    }
                }
                if (list1.size() > 0) {
                    map.put("list", list1);
                    List<Map<String, Object>> list2 = commonMapper.selAuthData0(map);
                    if (list2 != null && list2.size() > 0) {
                        list.addAll(list2);
                    }
                }
            } else {
                list = commonMapper.selAuthData(map);
            }
        }
        return Result.ok(list);
    }

    /**
     * 查询系统图标
     * @return 系统图标
     */
    public Result selIcons() {
        return Result.ok(commonMapper.selIcons());
    }

    // 获取展平码值
    public List<Map<String,Object>> getCodeTypeData2(Map<String,Object> paramMap){
        Map<String,Object> map=commonMapper.getTableName(paramMap);
        List<Map<String,Object>> list = commonMapper.getCodeList2(map);
        return list;
    }

    public Result getDataDict(String code) {
        List<DictVO> list = commonMapper.getDataDict(code);
        return Result.ok(TreeUtil.buildByRecursiveRootEmpty(list, null));
    }

    // 批量获取展平码值
    public Map<String,Object> getCodeTypeDataList(List<String> codeType){

        List<Map<String,Object>> list=commonMapper.getTableNameList(codeType);
        Map<String,Object> dataMap = new HashMap();
        for (int i = 0; i < list.size(); i++) {
            List<Map<String,Object>> datalist = commonMapper.getCodeList2(list.get(i));
            dataMap.put(list.get(i).get("codeType").toString(),datalist);
        }
        return dataMap;
    }
    //批量获取递归码值
    public List<Map<String, Object>> getRecurveCode(Map<String, Object> paramMap) {
        Map<String, Object> map = commonMapper.getTableName(paramMap);
        List<Map<String, Object>> list = commonMapper.getRecurveCode(map);
        return list;
    }

    /**
     * 附件上传
     * 廖昊源
     * @param multipartFile
     * @param seqno
     * @param userId
     * @param fileDatas
     * @return
     */
    @Transactional
    public Result uploadfile(MultipartFile[] multipartFile, String seqno, String userId, String fileDatas, String delfiles){
        JSONArray temp=JSONArray.parseArray(fileDatas);
        if (delfiles!=null){
            JSONArray delFileArr=JSONArray.parseArray(fileDatas);
            for (int i = 0; i < delFileArr.size(); i++) {
                Map<String,Object> delFileMap= JSON.parseObject(JSONArray.toJSONString(delFileArr.get(i)), HashMap.class);
                File fileUrl = new File(delFileMap.get("fileUrl").toString());
                fileUrl.delete();
                commonMapper.doDelCapExtFileUploadById(delFileMap.get("seqno").toString());
            }
        }
        CapBaseInfoConfigService infoConfigService = SpringContextUtil.getBean(CapBaseInfoConfigService.class);
        // 获取数据库中获取保存路径
        String url = infoConfigService.select(Constant.CAP_EXT_FILE_URL,Constant.SYSTEM_ENVIRONMENT);
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String fileFolderName = url +"/"+format.format(date);
        File file = new File(fileFolderName);
        for (int i = 0; i < temp.size(); i++) {
            Map<String,Object> map=JSON.parseObject(JSONArray.toJSONString(temp.get(i)), HashMap.class);
            String filePath=fileFolderName+"/"+UUID.randomUUID().toString()+map.get("fileType").toString();
            if(map.get("seqno") == null){
                if(!file.exists()){
                    file.mkdirs();
                }
                String fileName = multipartFile[i].getOriginalFilename();
                File dir = new File(filePath);
                try {
                    multipartFile[i].transferTo(dir);
                } catch (IOException e) {
                    throw new RuntimeException("文件上传失败" + e.getMessage());
                }
                CapExtFileUpload fileUpload =new CapExtFileUpload();

                fileUpload.setUploadUser(userId);
                fileUpload.setSeqno(redisUtil.getId());
                fileUpload.setAcctSeqno(seqno);
                fileUpload.setFileUrl(filePath);
                fileUpload.setFileName(map.get("fileName") == null ? "":map.get("fileName").toString());
                fileUpload.setFileDesc(map.get("fileDesc") == null ? "":map.get("fileDesc").toString());
                fileUpload.setUploadTime(new Date());
                commonMapper.doSaveCapExtLoanFileUpload(fileUpload);
            }
        }
        return Result.ok("导入成功");
    }

    public Result getFileList(String acctSeqno){
        List<Map<String,Object>> data = commonMapper.getFileList(acctSeqno);
        return Result.ok(data);
    }


    /**
     * 根据文件路径删除文件
     *
     * @param fileDel
     * @return
     */
    public Result delFile(FileDel fileDel) {
        // 获取文件路径
        String fileUrl = fileDel.getFileUrl();
//        String separator = File.separator;
//        String[] split = fileUrl.split("\\" + separator);
        try {
            // 根据文件路径删除文件
            File file = new File(fileUrl);
            if (file.exists()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 根据文件路径删除上传表中数据
        commonMapper.delFile(fileDel);
        return Result.ok(Constant.DELETE_OK_MSG);
    }

    public List<PriviInterCustom> selAllInterByUserId(Map<String, Object> map) {
        return  commonMapper.selAllInterByUserId(map);
    }

    public List<Index> selectIndex() {
        return commonMapper.selectIndex();
    }

    public void insertIndexData(Map<String, Object> map) {
        commonMapper.insertIndexData(map);
    }
}
